#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

/* Private functions decs */
int file_exist(char*filename);


int main(int argc, char *argv[]){

	FILE *fp,*fpOut;
	const char*fileOut = "acra_uboot_environment.h";
	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	if(argc!=2){
		printf("UBOOT ENV Converter.....\nConverts a copy-paste of the UBOOT environment\ninto a header"
				"file usable in UBOOT's compilation.\n");
		printf("Usage: convert [filename]\n");
		return 1;
	}

	/* Filename in should be a copy paste of the environment straight
	 * from UBOOT itself. */

	fp = fopen(argv[1], "r");
	if (fp == NULL){
		printf("That file does not exist mate.\n");
		exit(EXIT_FAILURE);
	}

	/* Test for existance of fileOut */
	if (file_exist((char*)fileOut)){
		/* File exists so warn */
		printf("Output file exists! Overwrite? (y/n):");

		if('y'!=getchar())
			exit(EXIT_SUCCESS);
	}

	fpOut = fopen(fileOut,"w");
	if (fpOut == NULL){
		printf("Couldn't open output file: %s\n", fileOut);
		exit(EXIT_FAILURE);

	}

	fprintf(fpOut, "#define CONFIG_EXTRA_ENV_SETTINGS \\\n");

	while ((read = getline(&line, &len, fp)) != -1) {
	//	printf("Retrieved line of length %zu :\n", read);

		if (read<2){
			printf("Skipping short line...\n");
			continue;
		}

		/* The getline function includes the newline character */
		line[strlen(line)-1]=0;

		fprintf(fpOut, "\"%s\\0\" \\\n", line);

	}

	fprintf(fpOut,"\"\"");

	fclose(fp);
	fclose(fpOut);

	free(line);
	exit(EXIT_SUCCESS);

	return 0;

}



int file_exist (char *filename)
{
  struct stat   buffer;
  return (stat (filename, &buffer) == 0);
}
